<template>
  <aside>
    <header>
      <n-avatar v-if="hasLogin" round :size="48" :src="userStore.userInfo.base64" @click="handleLogout"></n-avatar>
      <n-avatar v-else round :size="48" @click="controlDialog(true)">{{ $t('button.login') }}</n-avatar>
    </header>
    <HomeMenu />
    <HomeNavFooter />
  </aside>
  <n-modal v-model:show="showModal" :mask-closable="false">
    <n-card style="width: 360px" :bordered="false" size="huge" role="dialog" aria-modal="true">
      <template #header>
        <div class="modal_header">
          <p>{{ $t('button.userLogin') }}</p>
          <n-icon :size="18" @click="controlDialog(false)">
            <Close />
          </n-icon>
        </div>
      </template>
      <n-form :show-label="false" ref="formRef" :model="loginForm" :rules="loginFormRules"  @keydown.enter="handleValidateForm">
        <n-form-item path="userName">
          <n-input v-model:value="loginForm.userName" :placeholder="$t('placeholder.userNameHolder')" :disabled="loading" clearable />
        </n-form-item>
        <n-form-item path="password">
          <n-input v-model:value="loginForm.password" show-password-on="click" type="password" :disabled="loading" clearable
            :placeholder="$t('placeholder.passwordHolder')" />
        </n-form-item>
        <n-form-item>
          <n-button style="width:100%" type="primary" :disabled="loading" @click="handleValidateForm">
            <span>{{ $t('button.login') }}</span>
            <span v-show="loading" style="margin-left:1rem"> <n-spin stroke="#fff" :size="12" /></span>
          </n-button>
        </n-form-item>
      </n-form>
    </n-card>
  </n-modal>
</template>

<script setup lang='ts' name="HomeNav">
import { setToken,removeToken } from '@/utils/auth';
import { loginApi,getUserInfo } from '@/api/loginApi';
import { Close } from '@vicons/ionicons5';
import { FormInst, useMessage,useDialog } from 'naive-ui';
import { useUserStore } from '@/stores/user';
import HomeMenu from './HomeMenu.vue';
import i18n from '@/lang';
import HomeNavFooter from './HomeNavFooter.vue';

const { t } = i18n.global;
const dialog = useDialog();
const userStore = useUserStore();
const hasLogin = computed(()=>{
  return !!userStore.userInfo.id;
})
const showModal = ref(false);
const loading = ref(false);
const loginForm = reactive({
  userName: '',
  password: ''
});
const controlDialog = (bool:boolean) => {
  showModal.value = bool;
};
const formRef = ref<null | FormInst>(null);
const message = useMessage();
const loginFormRules = reactive<{
  'userName': {
    'message': string
    'required': boolean
    'trigger': string
  }
  'password': {
    'message': string
    'required': boolean
    'trigger': string
  }
}>({
  'userName': {
    'message': 'Please enter the ASG system account number',
    'required': true,
    'trigger': 'blur',
  },
  'password': {
    'message': 'Please enter your password',
    'required': true,
    'trigger': 'blur',
  },
});
const handleValidateForm = () => {
  formRef.value?.validate((errors)=>{
    if(!errors){
      login();
    }else{
      message.error(t('message.formWarning'));
    }
  })
}
// 登录
const login = async ()=>{
  try {
    loading.value = true;
    const result = await loginApi(loginForm) as string;
    setToken(result);
    const userInfo: UserInfo = await getUserInfo() as UserInfo;
    userStore.setUserInfos(userInfo);
    message.success(t('message.signInText'));
    controlDialog(false);
  } catch (error:any) {
    message.error(error.message ? error.message : error)
  } finally{
    loading.value = false;
  }
}
// 退出登录
const handleLogout = () => {
    dialog.warning({
        title: t('text.warning'),
        content: t('text.logoutText'),
        positiveText: t('text.confirm'),
        negativeText: t('text.cancel'),
        onPositiveClick: async () => {
            removeToken();
            userStore.clearUserInfo();
            message.success(t('text.outok'));
        },
    })
}
</script>
<style scoped lang='scss'>
aside {
  width: 100%;
  height: 100%;

  @include useTheme {
    background: getVar('navBarBg');
  }

  display:flex;
  flex-direction:column;
  align-items: center;

  header {
    width: 100%;
    padding: 1em 0;
    display: flex;
    justify-content: center;
    cursor: pointer;
  }
}

.modal_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  i{
    cursor: pointer;
    color:#333;
    &:hover{
      color:#f40;
    }
  }
}
</style>